package dao

import (
	"database/sql"
	"dm"
	"fmt"
	"github.com/kevinlisr/install-levault/sqldml"
	"github.com/kevinlisr/install-levault/vari"
	"strings"
)

type MysqlDB struct {
	db *sql.DB
}

func NewMysqlDB(db *sql.DB) *MysqlDB {
	return &MysqlDB{
		db: db,
	}
}

/* 查询产品信息表 */
func (d *MysqlDB) QueryTable(schemaName, tableName string) ([]string, error) {
	var url string
	var photo dm.DmBlob
	var urlMinio []string

	var sql = "SELECT url FROM " + schemaName + "." + tableName
	rows, err := d.db.Query(sql)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	fmt.Println("queryTable results:")
	for rows.Next() {
		if err = rows.Scan(&url); err != nil {
			return nil, err
		}
		blobLen, _ := photo.GetLength()
		urlMinio = append(urlMinio, url)
		fmt.Printf("%v %v\n", url, blobLen)
	}
	return urlMinio, nil
}

/* 修改数据 */
func (d *MysqlDB) UpdateTable(dmlsqls []string, url, username, pwd, dbtype, host, miniourlOld, miniourlNew string, port int) error {

	for _, dmlsql := range dmlsqls {
		stmt, err := d.db.Prepare(dmlsql)
		if err != nil {
			if strings.Contains(err.Error(), "无效的列名") {
				vari.Logger.Error(fmt.Sprintf("db prepare %s failed %s", dmlsql, "无效的列名"))
				continue
			} else {
				return fmt.Errorf("db prepare %s failed %s", dmlsql, err.Error())
			}

		}
		switch dmlsql {
		case sqldml.UPDATE_MYSQL_META_DATA_SOURCE_SQL:
			vari.Logger.Info(fmt.Sprintf("Start update META_DATA_SOURCE sql..."))
			res, err := stmt.Exec(url, username, dbtype, pwd)
			if err != nil {
				return fmt.Errorf("Update META_DATA_SOURCE SQL failed!")
			}
			affected, err := res.RowsAffected()
			if err != nil {
				vari.Logger.Error("RowsAffected failed!")
			}
			vari.Logger.Info(fmt.Sprintf("Update META_DATA_SOURCE SQL Success Affected %d Rows", affected))

		case sqldml.UPDATE_MYSQL_ML_DB_INFO_SQL:
			vari.Logger.Info(fmt.Sprintf("Start update ML_DB_INFO sql..."))
			res, err := stmt.Exec(url, host, dbtype, pwd, port, username)
			if err != nil {
				return fmt.Errorf("Update ML_DB_INFO SQL failed!")
			}
			affected, err := res.RowsAffected()
			if err != nil {
				vari.Logger.Error("RowsAffected failed!")
			}
			vari.Logger.Info(fmt.Sprintf("Update ML_DB_INFO SQL Success Affected %d Rows", affected))

		case sqldml.UPDATE_IMG_SQL:
			res, err := stmt.Exec(miniourlOld, miniourlNew, miniourlOld, miniourlNew)
			if err != nil {
				return fmt.Errorf("Update IMG SQL failed!")
			}
			affected, err := res.RowsAffected()
			if err != nil {
				vari.Logger.Error("RowsAffected failed!")
			}
			vari.Logger.Info(fmt.Sprintf("Update IMG SQL Success Affected %d Rows", affected))

		default:
			res, err := stmt.Exec(miniourlOld, miniourlNew)
			if err != nil {
				return fmt.Errorf("Update SQL failed!")
			}
			affected, err := res.RowsAffected()
			if err != nil {
				vari.Logger.Error("RowsAffected failed!")
			}
			vari.Logger.Info(fmt.Sprintf("Update SQL Success Affected %d Rows", affected))
		}
		vari.Logger.Info("updateTable succeed")
	}

	return nil
}
